<?php
/**
 * 路由
 */
class Route{
    
    private $m,$c,$a;
    

    public function __construct(){
        
        //模块域名绑定
        $bind_list=C('BIND_DOMAIN_LIST');
        if(is_array($bind_list)&&count($bind_list)&&isset($bind_list[$_SERVER['HTTP_HOST']])){
               define('M_NAME',strtolower($bind_list[$_SERVER['HTTP_HOST']]));
           }
        if(!empty($_SERVER['PATH_INFO'])){
            $this->urlParse();
            
        }else{
           $this->commonUrl();
        }
        
        defined('M_NAME')?'':define('M_NAME',strtolower(empty($this->m)?C('DEFAULT_M'):$this->m));
        define('C_NAME',strtolower(empty($this->c)?C('DEFAULT_C'):$this->c));
        define('A_NAME',strtolower(empty($this->a)?C('DEFAULT_A'):$this->a));
        
    }
    
    //pathinfo模式路由解析
    private function urlParse(){      
        
        $info= preg_replace('/\.'.C('EXT').'$/i','',strtolower(trim($_SERVER['PATH_INFO'],'/')));
        //加载路由配置文件
        if(is_file(CONFIG_PATH.'route.php')) {
            $routes=include CONFIG_PATH.'route.php';
        }
        
        if(!empty($routes)) {
            if(defined('M_NAME')){
                $routes=$routes[M_NAME];//如果绑定模块就使用模块路由
            }else{
                $path= explode('/',$info);
                if(array_key_exists($path[0],$routes)) {
                    $routes=$routes[$path[0]];
                }else{
                    $routes=$routes[C('DEFAULT_MODULE')];
                }
            }
            //执行正则路由匹配替换
            if(is_array($routes)&&!empty($routes)){
                foreach ($routes as $rule=>$route){
            
                    $route=trim($route,'/');
                    if(0===strpos($rule,'/') && preg_match($rule,$info)) {
                        $info=preg_replace ($rule,$route,$info);
                        break;
                    }
                }
            }
        }
        
        $path=explode('/',trim($info,'/'));//替换后的地址拆分
        
        //已绑定
        defined('M_NAME')&&$path[0]!=M_NAME&&array_unshift($path,M_NAME);//没有模块名

        $this->m=isset($path[0])?trim($path[0]):'';
        $this->c=isset($path[1])?trim($path[1]):'';
        $this->a=isset($path[2])?trim($path[2]):'';
        $count=count($path);
        if($count>3){
            for($i=3;$i<$count;$i=$i+2){
                 $_GET[$path[$i]]=isset($path[$i+1])?strip_tags($path[$i+1]):'';
              }
        }
        
    }
    
    private function commonUrl(){
        $this->m=isset($_GET['m'])&& !empty($_GET['m']) ? $_GET['m'] : (isset($_POST['m']) && !empty($_POST['m']) ? $_POST['m']:'');
        $this->c=isset($_GET['c'])&& !empty($_GET['c']) ? $_GET['c'] : (isset($_POST['c']) && !empty($_POST['c']) ? $_POST['c'] : '');
        $this->a=isset($_GET['a'])&& !empty($_GET['a']) ? $_GET['a'] : (isset($_POST['a']) && !empty($_POST['a']) ? $_POST['a'] :'');
        
    }

    
}